package test.ocr;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;

public class tess4jDemo {
    public static void main(String[] args) throws IOException {
        // 图片路径
        String path = "D:/img/2.jpg";
        // 语言位置
        String languagePath = "D:/tess4j";
//        File file = new File(path);
        Tesseract instance = new Tesseract();
        // 设置训练库位置
        instance.setDatapath(languagePath);
        // chi_sim:简体中文，eng根据需求选择语言库
        instance.setLanguage("chi_sim");
        String result = null;
        try {
            ByteArrayInputStream in = new ByteArrayInputStream(getByteArray(path));
            BufferedImage imageFile = ImageIO.read(in);
            result = instance.doOCR(imageFile);
        } catch (TesseractException e) {
            e.printStackTrace();
        }
        System.out.println("图片中的文字为:" + result);
    }

    public static byte[] getByteArray(String pathUrl) throws IOException {
        File file = new File(pathUrl);
        InputStream inputStream = new FileInputStream(file);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while (true) {
            try {
                if (!((rc = inputStream.read(buff, 0, 100)) > 0))
                    break;
            } catch (IOException e) {
                e.printStackTrace();
            }
            byteArrayOutputStream.write(buff, 0, rc);
        }
        inputStream.close();
        return byteArrayOutputStream.toByteArray();
    }

}